import { followCancel, followRequest } from '@/api/user'
import { ref } from 'vue'
import { useMessage } from './useMessage'
import { FollowStatus } from '@/enums'
import { UserInfo } from '@/types'
import { t } from '@/utils'
import { useProfileStore } from '@/store'

export const useFollow = () => {
	const message = useMessage()

	const loading = ref(false)

	const _followRequest = async (userInfo: UserInfo) => {
		try {
			loading.value = true
			const { data } = await followRequest({ followUserId: userInfo.userId })
			if (userInfo) {
				userInfo.followStatus = data?.status
				if (
					[
						FollowStatus.RequestedByMe,
						FollowStatus.MutualRequest,
						FollowStatus.MutualRequestFollowedByThem
					].includes(data?.status)
				) {
					message.success(t('follow.followRequestSuccess'))
				} else {
					const profileStore = useProfileStore()
					userInfo.follow = true
					userInfo.fanCount++
					message.success(t('follow.followSuccess'))
					if (profileStore.userInfo) {
						profileStore.patchUserInfo({ followCount: profileStore.userInfo.followCount + 1 })
					}
				}
			}
		} catch (err: any) {
			message.error(err)
		} finally {
			loading.value = false
		}
	}
	//	取消关注
	const _followCancel = async (userInfo: UserInfo) => {
		try {
			loading.value = true
			await followCancel({ id: userInfo.userId })
			message.success(t('follow.unfollowSuccess'))
			const profileStore = useProfileStore()
			if (profileStore.userInfo) {
				profileStore.patchUserInfo({ followCount: profileStore.userInfo.followCount - 1 })
			}
			//MutualFollow /FollowedByMe
			if (userInfo) {
				userInfo.follow = false
				userInfo.followStatus = FollowStatus.FollowedByMe
				userInfo.fanCount--
			}
		} catch (err: any) {
			message.error(err)
		} finally {
			loading.value = false
		}
	}

	return {
		loading,
		followRequest: _followRequest,
		followCancel: _followCancel
	}
}
